<template>
    <view class="Customers-info" :class="{ 'is-drawer-open': isDrawerStatus }">
        <view class="info-content">
            <view class="b-info">
                <CustomersInfoImg :avatar="avatar" :name="name" :cellphone="cellphone" :company="company"
                    :isShowCp="isShowCp" :isShowName="isShowName" :isDrawerStatus="isDrawerStatus"
                    @showCustmInfo="showCustmInfo">
                </CustomersInfoImg>
                <CustomersInfoBox :cellphone="cellphone" :district="district" :address="address" :amount="amount"
                    :num_xm="num_xm" :rece="rece" :price_count="price_count" :money="money" :md="md"
                    :isDrawerStatus="isDrawerStatus" :getYyInfoData="getYyInfoData" @countSaleMoney="countSaleMoney"
                    @payMoneyRece="paymentFlowMoney" @receMoney="receMoneyFun" @getRemainingItems="getRemainingItems"
                    @upInitData="loadsuppinfoFun" ref="customersInfoBoxRef">
                </CustomersInfoBox>
                <view class="c-list-box">
                    <CustomersInfoTxt :isDrawerStatus="isDrawerStatus" ref="customersInfoTxt" :md="md"
                        :customId="getYyInfoData.id" :getYyInfoData="getYyInfoData"></CustomersInfoTxt>
                </view>
                <template v-if="!isDrawerStatus">
                    <CustomersFixedBottom @optionAct="optionAct" :isOld="isOld" :md="xsgf || md"></CustomersFixedBottom>
                </template>
            </view>
            <view class="c-info" v-show="showInfo">
                <customerInfo :isShowCp="isShowCp" :isShowName="isShowName" :avatar="avatar" :name="name"
                    :company="company" :cellphone="cellphone" :email="email" :typeid_name="typeid_name"
                    :price_i_name="price_i_name" :ydListTitle="ydListTitle" :uid_cp="uid_cp" :remark="remark"
                    :from_name="from_name" @closeCustomInfo="closeCustomInfo">
                </customerInfo>
            </view>
        </view>
        <!-- 订单应收 -->
        <popFlowWin ref="popFlowWin" @cheTabType="cheTabType" @openReceMoneyWin="openReceMoneyWin" @loadMore="loadMore"
            @closePopFlowWin="closePopFlowWin"></popFlowWin>
        <!-- 收款，退款窗口 -->
        <payMent ref="payMent"></payMent>
        <!-- 二维码支付 -->
        <payQrcode ref="payQrcode"></payQrcode>
        <!-- 剩余服务 -->
        <popRemainingWin ref="popRemainingWin" :customId="getYyInfoData.id" @goAppointment="goAppointment"></popRemainingWin>
        <!-- 预付款 -->
        <popadvanceWin ref="popadvanceWin" @loadsuppinfoFun="loadsuppinfoFun" :md="md"></popadvanceWin>
        <!-- 跟进记录 -->
        <popFollowrecord ref="popFollowrecord"></popFollowrecord>
    </view>
</template>

<script>
import { useAppStore } from '@/store/piniaStore'
import { computed } from '@vue/composition-api'

import ordertoptitle from "../bills/OrderTopTitle.vue";
import CustomersInfoImg from "./CustomersInfoImg.vue";
import CustomersInfoBox from "./CustomersInfoBox.vue";
import CustomersInfoTxt from "./CustomersInfoTxt.vue";
import CustomersFixedBottom from "./CustomersFixedBottom.vue";
import customerInfo from "./CustomersInfo.vue";

import popFlowWin from "../comm/PopFlowWin.vue";
import popadvanceWin from "../comm/popadvanceWin.vue";
import popFollowrecord from "../comm/popFollowrecord.vue";

import customCtrl from "../../js/custom/CustomCtrl.js";
import https from "../../js/https/Https.js";
import lang from "../../js/conf/Lang.js";
import cmd from "../../js/Cmd.js";
import staticConst from "../../js/const/StaticConst.js";

import payMent from "../bills/PaymentMask.vue";

import config from "../../js/conf/Config.js";

import payQrcode from "../comm/PayQrcode.vue";
import popRemainingWin from "../comm/popRemainingWin.vue";

let pageSize = staticConst.PAGE_SIZE;

export default {

    // setup() {
    //     const appStore = useAppStore()
    //     const isD = computed(() => appStore.getCustomersDrawerStatus)
    //     console.log("xxxisDrawerStatuszz=", isD.value)
    //     return { isDrawerStatus }
    // },


    props: {
        md: {
            type: [String, Number],
            default: ''
        },
        xsgf: {
            type: [String, Number],
            default: ''
        },
        // 判定是否是从右边弹窗，嵌套进去的内容
        isDrawerOpen: {
            type: Boolean,
            default: false
        },
        // 客户id
        customerId: {
            type: String,
            default: ''
        }
    },
    components: {
        ordertoptitle,
        CustomersInfoImg,
        CustomersInfoBox,
        CustomersInfoTxt,
        CustomersFixedBottom,
        customerInfo,
        popFlowWin,
        payMent,
        payQrcode,
        popRemainingWin,
        popadvanceWin,
        popFollowrecord,
    },

    watch: {
        isDrawerOpen: {
            handler(newVal) {
                console.log("newVal=zz", newVal)
                if (newVal) {
                    this.isDrawerStatus = newVal;
                } else {
                    this.isDrawerStatus = false;
                }
            },
            deep: true,
            immediate: true
        },
        customerId: {
            handler(newVal) {
                console.log("customerId=", newVal)
                if (newVal) {
                    this.loadCustomInfo(newVal, true)
                }
            },
            immediate: true
        }
    },



    data() {
        return {
            title: "客户信息",
            showInfo: false,
            customInfo: null,
            customId: "",
            avatar: "", //客服头像
            name: "", //客服名称
            cellphone: "", //客户手机
            company: "", //客户公司名称

            address: "", //地址
            district: "", //省市区
            num_xm: "",
            amount: "", //累计销售
            rece: "", //初始欠款
            price_count: "", //订单应收
            money: "", //预付款
            isShowCp: true, //是否显示客户公司名称
            isShowName: true, //是否显示客户名称

            email: "", //邮箱地址
            typeid_name: "", //客户类别
            price_i_name: "", //默认报价
            uid_cp: "", //经手人吗
            ydListTitle: "", //开放云店
            ydList: [], //云店列表
            remark: "", //备注，
            remarkList: [], //备注列表
            from_name: "", //来源

            flowTitle: lang.customerTxt.countSaleFlowTxt, //累计流水记录标题

            paymentFlowTxt: lang.customerTxt.paymentFlowTxt, ////预付款流水标题
            pFlowPFrom: 0,
            payMentReceList: [], //预付款流水合并数据

            receTxt: lang.receTxt,
            receMoneyTxt: lang.customerTxt.receMoneyTxt,
            rFlowPFrom: 0, //应收款列表
            customMoerInfo: null,

            isOld: 1, //是否是老客户 1：是 ,其他不是

            allowPay: true,
            tab_type: 1,

            getYyInfoData: {},
            isDrawerStatus: false
        };
    },
    methods: {
        cheTabType(type) {
            this.tab_type = type;
            this.receMoney();
        },
        receMoneyFun() {
            this.tab_type = 1;
            this.receMoney();
        },
        closePopFlowWin() {
            console.log('closePopFlowWin==xt==:');
            if (this.$refs.popFlowWin) {
                this.$refs.popFlowWin.close();
            }
        },
        // 去预约
        goAppointment(item) {
            let data = {
                projectData: [item],
                customerInfo: this.customInfo,
            };
            data.projectData.map((v) => {
                v.serv_left = Number(v.serv_left);
                v.endtime_txt = v.endtime_str;
                v.serv_qty = 1;
                v.proid = v.id;
                v.title = v.gdname;
            });
            data.customerInfo.customerid = this.customInfo.id;
            console.log('data=xxxxxxxx=xxxx=', data)

            // 将数据存储到 store 中，而不是通过 URL 传递
            this.$store.commit('common/setAppointmentData', data);
            // 只传递必要的参数
            uni.navigateTo({
                url: `/pages/customerAppoint/index?act=5`,
            });
        },
        loadsuppinfoFun() {
            this.loadCustomInfo({ id: this.customMoerInfo.id });
        },
        getRemainingItems() {
            this.$refs.popRemainingWin.initData();
        },
        /***关闭客户详情**/
        showCustmInfo() {
            this.showInfo = !this.showInfo;
            cmd.external(cmd.CMD_SHOW_MORE, this.showInfo);
        },

        /****关闭客户详情******/
        closeCustomInfo() {
            this.showInfo = false;
            cmd.external(cmd.CMD_SHOW_MORE, this.showInfo);
        },

        /****编辑客户****/
        editCustomInfo(id) {
            this.loadCustomInfo(id, true);
        },

        /****获取预约客户详情*****/
        loadCustomInfoYy(obj, isEdit = false) {
            console.log(this.customerId, 'this.customerId')
            console.log(obj, 'obj')

            let that = this;
            let param = {
                is_yy: 1,
            };
            if (!isEdit) {
                this.customInfo = obj;
                this.customId = obj.id;
                param.id = obj.id;
            } else {
                this.customId = obj;
                param.id = obj;
            }
            https.getCustomInfo(param, back);
            function back(data) {
                if (!data.data) {
                    that.clearData();
                    that.$refs.customersInfoTxt.initData(this.customerId || 0);
                    return;
                }
                that.getYyInfoData = JSON.parse(JSON.stringify(data.data));
                console.log(that.getYyInfoData, 'getYyInfoDatagetYyInfoDatagetYyInfoDatagetYyInfoData')
            }
        },
        /****获取客户详情*****/
        async loadCustomInfo(obj, isEdit = false) {
            console.log("loadCustomInfo==obj==", obj)
            // 保存用户信息到store 中，方便其他操作使用
            this.$store.commit('common/set_customer_index_v2', obj);
            await this.clearData();
            let that = this;
            let param = {};
            if (!isEdit) {
                this.customInfo = obj;
                this.customId = obj.id;
                param.id = obj.id;
            } else {
                this.customId = obj;
                param.id = obj;
            }
            param.is_yy = this.md == staticConst.YY_GK ? 1 : 0; //是否预约 1是 其他否 默认否
            this.loadCustomInfoYy(obj, isEdit = false)
            https.getCustomInfo(param, back);
            function back(data) {
                // that.loadCustomInfoYy(obj, isEdit = false)
                if (!data.data) {
                    that.clearData();
                    that.$refs.customersInfoTxt.initData(this.customerId || 0);
                    return;
                }
                data = data.data;
                that.customMoerInfo = data;
                that.customInfo = data;
                if (data.avatar) that.avatar = data.avatar;
                if (data.name) that.name = data.name;
                if (data.cellphone) that.cellphone = data.cellphone;
                if (data.company) that.company = data.company;
                if (data.address) that.address = data.address;
                if (data.district) that.district = data.district;
                if (data.num_xm)
                    //累计销售
                    that.num_xm = data.num_xm;
                if (data.amount)
                    //累计销售
                    that.amount = data.amount;
                if (data.rece)
                    //初始欠款
                    that.rece = data.rece;
                if (data.price_count)
                    //订单应收
                    that.price_count = data.price_count;
                if (data.money)
                    //预付款
                    that.money = data.money;

                if (data.email)
                    //邮箱地址
                    that.email = data.email;
                if (data.typeid_name)
                    //客户类别
                    that.typeid_name = data.typeid_name;
                if (data.price_i_name)
                    //默认报价
                    that.price_i_name = data.price_i_name;
                if (data.uid_cp)
                    //经手人吗
                    that.uid_cp = data.uid_cp;
                that.isOld = data.isold; //是否是老客户

                if (data.yd_ls) {
                    //开放云店
                    that.ydList = data.yd_ls;
                    let len = that.ydList.length;
                    for (let i = 0; i < len; i++) {
                        let obj = that.ydList[i];
                        that.ydListTitle +=
                            that.ydListTitle == "" ? obj.name : "," + obj.name;
                    }
                }
                if (that.md == 15 && data.yunid_name) {
                    that.ydListTitle = data.yunid_name;
                }
                if (that.md == 15 && data.yy_price_i_name) {
                    that.price_i_name = data.yy_price_i_name;
                }
                if (data.remark)
                    //备注，
                    that.remark = data.remark;
                if (data.from_name)
                    //来源
                    that.from_name = data.from_name;

                that.$refs.customersInfoTxt.listIndex = 0;
                that.$refs.customersInfoTxt.curTabId = 1;
                that.$refs.customersInfoTxt.initData(data.id);

                if (isEdit) {
                    let cData = {};
                    cData.id = data.id;
                    cData.avatar = data.avatar;
                    if (data.tag_title)
                        cData.tag = String(data.tag_title).split(",");
                    else cData.tag = [];
                    cData.cellphone = data.cellphone;
                    cData.name = data.name;
                    cData.company = data.company;
                    cData.isold = data.isold;
                    cData.isold_name = data.isold_name;
                    that.$emit("updataCustomList", cData);
                }
            }

            this.isShowCp = customCtrl.getIsShowCp();
            this.isShowName = customCtrl.getIsShowName();
            this.$forceUpdate();
        },

        clearData() {
            this.customInfo = null; //列表客户信息
            this.customMoerInfo = null;
            this.avatar = ""; //客服头像
            this.name = ""; //客服名称
            this.cellphone = ""; //客户手机
            this.company = ""; //客户公司名称
            this.address = ""; //地址
            this.district = ""; //省市区
            this.amount = ""; //累计销售
            this.rece = ""; //初始欠款
            this.price_count = ""; //订单应收
            this.money = ""; //预付款
            this.email = ""; //邮箱地址
            this.typeid_name = ""; //客户类别
            this.price_i_name = ""; //默认报价
            this.uid_cp = ""; //经手人吗
            this.ydListTitle = ""; //开放云店
            this.ydList = []; //云店列表
            this.remark = ""; //备注，
            this.remarkList = []; //备注列表
            this.from_name = ""; //来源

            this.pFlowPFrom = 0;
            this.rFlowPFrom = 0;
            this.isOld = 1;
            this.allowPay = true;
        },

        getCustomerData() {
            let param = {
                allCount: 0.0,
                customerid: this.customInfo.id,
                totalMoney: 0.0,
            };
            let url = config.YY_ORDER_CART_SAVE;
            this.$api({ url: url, data: param });
        },
        optionAct(act) {
            console.log("操作===act==:", act);
            if (act == 0)
                //删除客户
                this.removeCustomTipWin();
            else if (act == 1) {
                if (this.md == staticConst.YY_GK) {
                    this.getCustomerData();
                    uni.navigateTo({
                        url: `/pages/appointmentBilling/index`,
                    });
                } else {
                    this.bill();
                }
            }
            //开单
            else if (act == 2) this.editCustomer();
            else if (act == 3) this.changOldCustom();
            else if (act == 4) {
                const data = {
                    api: config.CUSTOM_RECE_SAVE,
                    obj: this.customMoerInfo,
                    param: {
                        is_yy: 1,
                        customerid: this.customMoerInfo.id,
                    },
                };
                this.$refs.popadvanceWin.initData(data);
            }
        },

        /****是否转成老客户****/
        changOldCustom() {
            let that = this;
            let data = {};
            data.content = lang.customerTxt.changOldTip;
            data.showCancel = true;
            lang.showWin(data, back);
            function back(res) {
                if (res.confirm) {
                    let param = {};
                    param.id = that.customInfo.id;
                    https.customChangeOld(param, callBack);
                }
            }

            function callBack(obj) {
                if (!obj) return;
                if (obj.status == 1) {
                    that.isOld = 1;
                    let cData = {};
                    cData.id = that.customInfo.id;
                    cData.avatar = that.customInfo.avatar;
                    cData.tag = that.customInfo.tag;
                    cData.cellphone = that.customInfo.cellphone;
                    cData.name = that.customInfo.name;
                    cData.company = that.customInfo.company;
                    cData.isold = that.isOld;
                    cData.isold_name = "";
                    that.$emit("updataCustomList", cData);
                }
            }
        },

        /****弹出删除客户提示窗口****/
        removeCustomTipWin() {
            if (!this.customInfo) return;
            let that = this;
            let data = {};
            data.title = lang.deleTitTxt;
            data.content = lang.customerTxt.delTxt;
            data.showCancel = true;
            lang.showWin(data, back);
            function back(res) {
                if (res.confirm) {
                    that.closeCustomInfo();
                    that.remove();
                }
            }
        },

        /****删除客户****/
        remove() {
            let that = this;
            let param = {};
            param.id = this.customInfo.id;
            https.delCustom(param, back);
            function back(data) {
                if (!data) return;
                if (data.status == 1) {
                    that.$emit("removeCustom", that.customInfo.id);
                }
            }
        },

        /********开单******/
        bill() {
            if (!this.customInfo) return;
            let that = this;
            that.$emit("bill", that.customInfo);
            return
            let data = {};
            data.title = lang.receiptTxt.titleTxt;
            data.content = lang.customerTxt.billTxt;
            data.showCancel = true;
            lang.showWin(data, back);
            function back(res) {
                if (res.confirm) {
                    that.$emit("bill", that.customInfo);
                }
            }
        },

        /***编辑客户****/
        editCustomer() {
            console.log(this.customMoerInfo);
            if (!this.customMoerInfo) return;
            this.$emit("editCustomer", this.customMoerInfo);
        },

        /*******累计销售流水*******/
        countSaleMoney(type, openType = true) {
            if (!this.customInfo) return;
            let that = this;
            let param = {};
            param.page = 0;
            param.customerid = this.customInfo.id;
            if (type == 'yy') {
                param.is_yy = 1;
                param.pfrom = 0;
                param.pnum = 20;
                https.customAmountList(param, back);
            } else {
                https.customAmountList2(param, back);
            }
            function back(data) {
                if (!data) return;
                if (data.status == 1) {
                    if (!data.data) return that.$message.error(data.msg || "暂无数据");;
                    data = data.data;
                    let obj = {};
                    obj.list = data;
                    obj.objType = 1;
                    obj.title = type == 'yy' ? "累计预约流水" : that.flowTitle;
                    obj.md = type == 'yy' ? 15 : '';
                    that.$refs.popFlowWin.show("show", obj, openType);
                } else {
                    that.$message.error(data.msg || "暂无数据");
                }
            }
        },

        /*********预付款流水***** 预付款 *******/
        paymentFlowMoney(openType = true) {
            if (!this.customInfo) return;
            this.pFlowPFrom = 0;
            let that = this;
            let param = {};
            param.customerid = this.customInfo.id;
            param.pnum = pageSize;
            param.is_yy = 0;
            param.pfrom = this.pFlowPFrom * pageSize;
            https.customReceList(param, back);
            function back(data) {
                if (!data) return;
                if (data.status == 1) {
                    if (!data.data) return that.$message.error(data.msg || "暂无数据");
                    data = data.data;
                    if (!data) data = [];
                    let obj = {};
                    obj.list = magrePayMentReceList(data);
                    obj.objType = 2;
                    obj.title = that.paymentFlowTxt;
                    that.pFlowPFrom++;
                    that.$refs.popFlowWin.show("show", obj, openType);
                    // that.$refs.customersInfoBoxRef.show("show", obj);
                } else {
                    that.$message.error(data.msg || "暂无数据");
                }
            }

            function magrePayMentReceList(arr) {
                that.payMentReceList.map((v) => {
                    v.list = [];
                });
                let leng = arr.length;
                for (let i = 0; i < leng; i++) {
                    let temp = arr[i];
                    let hasIdx = -1;
                    let len = that.payMentReceList.length;

                    for (let j = 0; j < len; j++) {
                        let tObj = that.payMentReceList[j];
                        if (tObj.atime == temp.atime) {
                            hasIdx = j;
                            break;
                        }
                    }
                    let t = {};
                    t.money = temp.money;
                    t.payinfo = temp.payinfo;
                    t.uid_cp = temp.uid_cp;
                    t.uid_name = temp.uid_name;
                    t.id = temp.id;
                    t.atime = temp.atime;
                    t.txt = temp.txt;
                    if (hasIdx != -1) {
                        //有相同日期
                        let tList = that.payMentReceList[hasIdx].list;

                        tList.push(t);
                        that.payMentReceList[hasIdx].list = tList;
                    } else {
                        //添加新的日期
                        let obj = {};
                        obj.atime = temp.atime;
                        obj.list = [];
                        obj.list.push(t);
                        that.payMentReceList.push(obj);
                    }
                }
                return that.payMentReceList;
            }
        },

        /*****应收订单列表***订单应收***/
        // {
        //     app: "pc"
        //     customerid: "10"
        //     is_ajax: 1
        //     is_yy: 0
        //     pfrom: 0
        //     pnum: 20
        // }
        receMoney(openType = true) {
            if (!this.customInfo) return;
            this.rFlowPFrom = 0;
            let that = this;
            let param = {};
            param.customerid = this.customInfo.id;
            param.pnum = pageSize;
            param.is_yy = that.tab_type == 2 ? 1 : 0;
            param.pfrom = this.rFlowPFrom * pageSize;
            https.customOrderReceList(param, back);
            function back(data) {
                if (!data) return;
                if (data.status == 1) {
                    if (!data.data) return that.$message.error(data.msg || "暂无数据");
                    data = data.data;
                    let obj = {};
                    obj.objType = 3;
                    obj.title = that.receMoneyTxt;
                    obj.list = data.order_ls || [];
                    obj.od_detail_all = data.od_detail_all || [];
                    obj.tab_type = that.tab_type;
                    obj.recedata = {
                        recdid: data.recdid,
                        rece: data.rece,
                        id: data.recdid,
                    };
                    that.rFlowPFrom++;
                    console.log('obj==xt==:', obj);
                    that.$refs.popFlowWin.show("show", obj, openType);
                } else {
                    that.$message.error(data.msg || "暂无数据");
                }
            }
        },

        /*****加载更多******/
        loadMore() {
            this.rFlowPFrom++;
            this.receMoney(false);
        },

        async openReceMoneyWin(item) {
            if (!item) return;
            if (!this.allowPay) {
                return;
            }
            let that = this;
            let param = {};
            let url = that.tab_type == 2 ? config.YY0_ORDER_PAY : config.ORDER_PAY;

            param.type = 1; //this.orderInfos.type;
            param.odid = item.id;
            param.act = "topay";

            let res = await this.$api({ url: url, data: param });
            if (!res) return;
            if (res.status == 1) {
                if (!res.data) return that.$message.error(res.msg || "暂无数据");
                let obj = {};
                obj = res.data;
                obj.act = "pay_in";
                obj.odid = item.id;
                obj.type = 1;
                obj.callBack = topayAction;
                this.$refs.payMent.toggleBillsStateMask("show", obj);
            } else {
                that.$message.error(res.msg || "暂无数据");
            }

            async function topayAction(data) {
                console.log("topayAction====:", data);
                if (data.payid >= 1000) {
                    //线下收款
                    let param = data;
                    let url =
                        that.md == 15 ? config.YY0_ORDER_PAY : config.ORDER_PAY;
                    let res = await that.$api({ url: url, data: param });
                    if (!res) return;
                    if (res.status == 1) {
                        console.log("topayAction====:", res);
                        that.$msg({ title: res.msg });
                        if (!res.data || !res.data.amount_notpay) return;
                        let obj = {};
                        obj.odid = data.odid;
                        obj.amount_notpay = res.data.amount_notpay;
                        setTimeout(() => {
                            that.$refs.payMent.toggleBillsStateMask("close", {});
                        }, 300);
                        that.$refs.popFlowWin.updateNotPayMoney(obj);
                    }
                } else {
                    let obj = {};
                    obj.payType = data.paytype;
                    obj.objtype = staticConst.PAY_OBJ_01; //data.objtype;
                    obj.odid = data.odid;
                    obj.money_pay = data.amount_receive;
                    that.$refs.payQrcode.creatQrcode(obj);
                }
            }
        },
    },
};
</script>
<style lang="scss">
.Customers-info {
    flex: 1;
    margin-left: 345px;
    height: 100vh;
    background-color: #fff;

    .c-list-box {
        // overflow-y:auto;
        height: calc(100vh - 363px);
    }

    .info-content {
        display: flex;
    }

    .b-info {
        width: 100%;
        border-right: 1px solid #ececec;
        background: #fff;
    }

    .c-info {
        // width: 310px;
        // height: 100%;
    }
}

.is-drawer-open {
    margin-left: 0px !important;
    height: 90vh !important;
}
</style>